package com.vnp.vchat.version2;

import org.json.JSONException;
import org.json.JSONObject;

import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.R;
import com.vnp.vchat.R.layout;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

public class GetAccountByPhoneOrEmailActivity extends Activity implements
		OnClickListener {

	TextView title;
	EditText edtTk;
	Button btnTieptuc;

	PreferenceHelper preferenceHelper;
	String name;
	Handler mHandler = new Handler();
	Runnable r = new Runnable() {

		@Override
		public void run() {
			KeyboardHelper.displaySoftKeyboard(
					GetAccountByPhoneOrEmailActivity.this, edtTk);
		}
	};

	String accID;

	private BroadcastReceiver mReceiver;

	ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_get_account_by_phone_or_email);
		
		preferenceHelper = new PreferenceHelper(this);
		
		title = (TextView) findViewById(R.id.title);
		edtTk = (EditText) findViewById(R.id.edt_phone_email);
		btnTieptuc = (Button) findViewById(R.id.btn_tieptuc);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		
		setFont();
		init();
		nhapTaikhoan();
		
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 300);
		
		recivedBroadcast();
		
	}

	private void recivedBroadcast() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("HUY");

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				finish();
			}
		};

		// register
		this.registerReceiver(mReceiver, intentFilter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}

	void init() {
		title.setText("Đăng nhập");
		btnTieptuc.setOnClickListener(this);
		btnTieptuc.setText("Tiếp tục");
	}

	void nhapTaikhoan() {
		edtTk.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT) {
					checkLogin();
					return true;
				}
				return false;
			}
		});

	}

	void getAccount() {
		
		progressBar.setVisibility(View.VISIBLE);
		
		KeyboardHelper.hideSoftKeyboard(GetAccountByPhoneOrEmailActivity.this);
		btnTieptuc.setText("Đang đăng nhập...");
		edtTk.setEnabled(false);
		btnTieptuc.setClickable(false);

		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(int statusCode, Throwable error) {
						if (statusCode == 400) {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							Toast.makeText(
									GetAccountByPhoneOrEmailActivity.this,
									"Số điện thoại không đúng",
									Toast.LENGTH_SHORT).show();
							edtTk.requestFocus();
							KeyboardHelper.displaySoftKeyboard(
									GetAccountByPhoneOrEmailActivity.this,
									edtTk);
						} else if (statusCode == 404) {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							gotoDangki();
							// sendPhone();
						}
					}

					@Override
					public void onSuccess(int statusCode, JSONObject re) {
						if (statusCode == 200) {
							Log.i("LOGIN", "GETACOUNT: " + re.toString());
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							try {
								String firtName = re.getJSONObject("account")
										.getString("first_name");
								String lastname = re.getJSONObject("account")
										.getString("last_name");
								
								name = firtName + " " + lastname;
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							gotoPass();
						}
					}
					
					

				});

//		httpClientHelper.getAccountByPhone(edtTk.getText().toString());
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					
					try {
						String firtName = re.getJSONObject("account")
								.getString("first_name");
						String lastname = re.getJSONObject("account")
								.getString("last_name");
						
						name = firtName + " " + lastname;
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							gotoPass();
						}
					});
					Log.i("LOGIN", "GETACOUNT: " + re.toString());
					
				} else if (statusCode == 400) {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							Utils.showToast(GetAccountByPhoneOrEmailActivity.this, "Số điện thoại không đúng");
							edtTk.requestFocus();
							KeyboardHelper.displaySoftKeyboard(
									GetAccountByPhoneOrEmailActivity.this,
									edtTk);
						}
					});
				} else if (statusCode == 404) {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);	
							gotoDangki();
						}
					});
					
				}
				Log.i("LOGIN", "LOGIN: "+httpResponse.getStatus()+ " "+re.toString());
			}

			@Override
			public void onFailure(Exception e) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						progressBar.setVisibility(View.GONE);
						btnTieptuc.setText("Tiếp tục");
						edtTk.setEnabled(true);
						btnTieptuc.setClickable(true);
						Utils.showToast(GetAccountByPhoneOrEmailActivity.this, "Lỗi kết nối.");
						edtTk.requestFocus();
						KeyboardHelper.displaySoftKeyboard(
								GetAccountByPhoneOrEmailActivity.this,
								edtTk);
					}
				});
			}
			
			
			
		});
		
		httpBasicClientHelper.getAccountByPhone(edtTk.getText().toString());
		
		
	}

	void setFont() {
		title.setTypeface(Utils
				.getTypefaceBold(GetAccountByPhoneOrEmailActivity.this));
		edtTk.setTypeface(Utils
				.getTypefaceRegular(GetAccountByPhoneOrEmailActivity.this));
		btnTieptuc.setTypeface(Utils
				.getTypefaceMedium(GetAccountByPhoneOrEmailActivity.this));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tieptuc:
			checkLogin();
			break;

		default:
			break;
		}
	}

	void checkLogin() {
		if (edtTk.getText().toString().equals("")) {
			
			Utils.showToast(GetAccountByPhoneOrEmailActivity.this, "Tài khoản không được để trống!");
			
		} else {
			getAccount();
		}
	}

	void gotoPass() {
		preferenceHelper.setPhone(edtTk.getText().toString());
		Intent t = new Intent(GetAccountByPhoneOrEmailActivity.this,
				NhapPassActivity.class);
		t.putExtra("username", edtTk.getText().toString());
		t.putExtra("name", name);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}

	void gotoDangki() {
		Intent t = new Intent(GetAccountByPhoneOrEmailActivity.this,
				DangkiNhapCodeActivity.class);
		t.putExtra("phone", edtTk.getText().toString());
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}

	void sendPhone() {

		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, JSONObject re) {
						if (statusCode == 200) {
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							Log.i("NHAPPHONE", "TRA VE: " + re.toString());
							try {
								accID = String.valueOf(re.getInt("acc_id"));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							gotoNhapMaCode();
						}
					}

					@Override
					public void onFailure(int statusCode, Throwable error) {
						if (statusCode == 400) {
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							Toast.makeText(
									GetAccountByPhoneOrEmailActivity.this,
									"Số điện thoại không đúng.",
									Toast.LENGTH_SHORT).show();
						} else if (statusCode == 403) {
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							error.printStackTrace();
							Toast.makeText(
									GetAccountByPhoneOrEmailActivity.this,
									"Số điện thoại đã tồn tại trên hệ thống.",
									Toast.LENGTH_SHORT).show();
						}

					}

				});

		httpClientHelper.sendPhone(edtTk.getText().toString());
	}

	void gotoNhapMaCode() {
		Intent t = new Intent(GetAccountByPhoneOrEmailActivity.this,
				DangkiNhapCodeActivity.class);
		t.putExtra("acc_id", accID);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}

}
